<?php
namespace app\bbs\controller;
use x\Xbase;
use x\my\Pay;
class Notice extends Xbase{
  //微信异步通知
  public function wxpay(){
      $con = c('api.wx_gzh_config.myb');
      $config = [
          'app_id'  => $con['app_id'],
          'mch_id'  => $con['mch_id'],
          'key'     => $con['key'],
          'mode'    => 'optional',
          // 'notify_url' => url('notice/wxpay'),
      ];
      $pay = Pay::wechat($config);
      $result = $pay->verify();
      #更新订单
      $rs = $this->db->query('select id,user_id,xiangmu_id,order_no,year from order_xiangmu where order_no=?',[$result->out_trade_no],1);
      $pay_order_no = $result->transaction_id;
      $this->db->begin();
      $mysql = [];
      //处理订单
      $pay_data = json_encode($result,JSON_UNESCAPED_UNICODE);
      //log_test('wxpay',json_decode($pay_data,true));
      $d = [
          'id'=>$rs['id'],
          'pay_status'=>1,
          'pay_order_no'=>$pay_order_no,
          'pay_data' => $pay_data,
          'update_time'=>time()
      ];
      $mysql[] = $this->db->update('order_xiangmu',$d);
      //支付记录
      $data = [
          'type' => 0,
          'tab' => 'order_xiangmu',
          'tab_id' => $rs['id'],
          'tab_order_no' => $rs['order_no'],
          'pay_order_no' => $pay_order_no,
          'money' => 0,
          'pay_data' => $pay_data,
          'create_time'=>time()
        ];
      $mysql[] = $this->db->insert('order_pay', $data);


      //user_xiangmu, 项目权限
      $res = $this->db->query('select id,xiangmu_id,end_time from user_xiangmu where user_id=? and xiangmu_id=?',[$rs['user_id'],$rs['xiangmu_id']],1);
      //延长权限时间
      if($res){
        $time = $res['end_time'] > time() ? $res['end_time'] : time();
        $data = [
            'id' => $res['id'],
            'end_time' => $res['year'] ? strtotime("+{$res['year']} year", $time) : strtotime("+7 day", $time),
            'update_time'=>time()
        ];
        $mysql[] = $this->db->update('user_xiangmu', $data);
      }else{
        $data = [
            'user_id' => $rs['user_id'],
            'xiangmu_id' => $rs['xiangmu_id'],
            'end_time' => $rs['year'] ? strtotime("+{$rs['year']} year") : strtotime("+7 day"),
            'create_time'=>time()
        ];
        $mysql[] = $this->db->insert('user_xiangmu', $data);
      }
      $res = $this->db->end($mysql);
      if($res){
        $pay->success()->send();
      }
      exit;
  }
}
